﻿using lingopen.Foxconn.BLE.Com;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace lingopen.Foxconn.BLE.Reader
{
    /// <summary>
    /// ble 阅读器实例
    /// </summary>
    public class BLEReader
    {
        static AsyncTcpServer server;
        static RichTextBoxLog _log = null;
        public BLEReader(RichTextBox rtxt)
        {
            _log = new Com.RichTextBoxLog(rtxt);
        }
        void Start(string ip,int port)
        {
            //server = new AsyncTcpServer(IPAddress.Parse("192.168.31.103"), 9999);
            server = new AsyncTcpServer(IPAddress.Parse(ip), port);
            server.Encoding = Encoding.UTF8;
            server.ClientConnected +=
              new EventHandler<TcpClientConnectedEventArgs>(server_ClientConnected);
            server.ClientDisconnected +=
              new EventHandler<TcpClientDisconnectedEventArgs>(server_ClientDisconnected);
            server.PlaintextReceived +=
              new EventHandler<TcpDatagramReceivedEventArgs<string>>(server_PlaintextReceived);
            server.Start();
            //$"{ip}:TCP server has been started.".Log();
            _log.LogMessage($"{ip}:TCP server has been started.");
            //"Type something to send to client...".Log();

            //while (true)
            //{
            //    string text = Console.ReadLine();
            //    server.SendAll(text);
            //}
        }

        static void server_ClientConnected(object sender, TcpClientConnectedEventArgs e)
        {
            //(string.Format(CultureInfo.InvariantCulture,
            //  "TCP client {0} has connected.",
            //  e.TcpClient.Client.RemoteEndPoint.ToString())).Log();

            _log.LogMessage(string.Format(CultureInfo.InvariantCulture,
              "TCP client {0} has connected.",
              e.TcpClient.Client.RemoteEndPoint.ToString()));
        }

        static void server_ClientDisconnected(object sender, TcpClientDisconnectedEventArgs e)
        {
            _log.LogMessage(string.Format(CultureInfo.InvariantCulture,
              "TCP client {0} has disconnected.",
              e.TcpClient.Client.RemoteEndPoint.ToString()));
        }

        static void server_PlaintextReceived(object sender, TcpDatagramReceivedEventArgs<string> e)
        {
            string res = e.Datagram.Replace("\r\n", "").Replace("+INQRESULT:", "");
            string[] fields = res.Split(',');
            if (fields.Length != 6 || fields[2] != "\"Jinou_Beacon\"") return;
            // Console.WriteLine(res);
            //res = "D776A8FEB78E,0,\"Jinou_Beacon\",4,0D094A696E6F755F426561636F6E,-48";
            _log.LogWarning(res);
        }
    }
}
